package com.whfc.iot.mach.server;

import com.whfc.iot.codec.CustomLengthFieldBasedFrameDecoder;
import com.whfc.iot.mach.codec.MachMsgDecoder;
import com.whfc.iot.mach.codec.MachMsgEncoder;
import com.whfc.iot.server.IotServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Description: 机械管家socket服务器
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/16 18:33
 */
@Component
public class MachServer implements IotServer {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 端口
     */
    private int port;

    @Autowired
    private MachServerHandler machServerHandler;

    @Override
    public void port(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        logger.info("socket服务器开始启动,port:{}", port);
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //ch.pipeline().addLast(new LoggingHandler());
                            ch.pipeline().addLast(new CustomLengthFieldBasedFrameDecoder(1024, 7, 2, -9, 0));
                            ch.pipeline().addLast(new IdleStateHandler(6, 0, 0, TimeUnit.MINUTES));
                            ch.pipeline().addLast(new MachMsgDecoder());
                            ch.pipeline().addLast(new MachMsgEncoder());
                            ch.pipeline().addLast(machServerHandler);
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);

            ChannelFuture future = serverBootstrap.bind(port).syncUninterruptibly();
            future.channel().closeFuture().syncUninterruptibly();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
